import * as ctiTypes from '../cti/mutation-types'
import * as callTypes from '../call/mutation-types'
import * as ctiAction from '../cti/actions'
import * as types from './mutation-types'
import * as webchatTypes from '../webchat/mutation-types'
import {getCache, getCacheByKey} from '../../actions'
import monitor from '../../api/monitor'
import report from '../../api/report'
import {dealReportRes} from '@/utils/m7Utils'
import { filter } from 'lodash'
import * as globalTypes from '../../mutation-types'
import http from '../../api/http'
import globalField from '../../../components/public-modules/global-filed' // 引用模块进来
// let dataJson = null
/**
 * 初始化
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @returns {Promise<R>|Promise.<T>}
 * @private
 */
export const imMonitorInit = ({commit, state, rootState, dispatch}) => {
  // 初始化坐席列表
  let p1 = getCache({commit, state: rootState}, {type: 'agents'}).then(agents => {
    commit(types.INIT_MONITOR_AGENTS, {agents})
  })
  // 初始化服务号列表
  let p2 = getCache({commit, state: rootState}, {type: 'webchatAndSdkConfig'}).then(config => {
    commit(types.INIT_MONITOR_IM_CHANNEL, {config})
  })
  let p = Promise.all([p1, p2])
  return p.then(() => {
    // 获取坐席和技能组数据
    return monitor.getPushOnlineAgentAndDealingCount({})
      .then(response => {
        console.log(response)
        let p1 = getCache({commit, state: rootState}, {type: 'mailQueues'})
        let p2 = getCache({commit, state: rootState}, {type: 'onlineChannelAgent'})
        let p = Promise.all([p1, p2])
        return p.then(([mailQueues, onlines]) => {
          console.log(response)
          // 初始化坐席和技能组数据
          commit(types.INIT_AGENT_AND_QUEUE, {res: response, mailQueues, onlines})
        })
      })
  }).then(() => {
    // 获取坐席和服务号数据
    return monitor.queryMonitorInitData({account: rootState.session.account.account})
      .then(response => {
        if (response.success) {
          // 初始化坐席和服务号数据
          commit(types.INIT_MONITOR_ACCESSNO, {res: response})
        }
      })
  }).catch(err => {
    console.log(err)
    // 'message.default_tips'
  })
}
/**
 * im推送处理
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @returns {Promise<R>|Promise.<T>}
 * @private
 */
export const imMonitorEventProcess = ({commit, state, rootState, dispatch}, event) => {
  event = event.Data
  if (rootState.monitor.moduleOpen.webchat) {
    // 监控
    if (event.im_monitor_type === 'accessNo') {
      return getCache({commit, state: rootState}, {type: 'webchatAndSdkConfig'}).then(() => {
        return getCacheByKey({commit, state: rootState}, {
          type: 'webchatAndSdkConfig',
          key: 'accessId',
          value: event.accessId
        })
      }).then(curAccess => {
        commit(types.EVENT_MONITOR_IM_CHANNEL, {event, curAccess})
      }).catch(err => {
        console.log(err)
        // 'message.default_tips'
      })
    } else if (event.im_monitor_type === 'agent') {
      commit(types.EVENT_MONITOR_IM_AGENT, {event})
    } else if (event.im_monitor_type === 'queue') {
      return getCache({commit, state: rootState}, {type: 'mailQueues'}).then(() => {
      }).then(() => {
        getCacheByKey({commit, state: rootState}, {
          type: 'mailQueues',
          key: 'Exten',
          value: event.queueExten
        }).then((curQueue) => {
          commit(types.EVENT_MONITOR_IM_QUEUE, {event, curQueue})
        })
      }).catch(err => {
        console.log(err)
        // 'message.default_tips'
      })
    }
  }
  // 通知
  if (event.type === 'warning') {
    let message = event.message
    let data = {
      condition: message.condition,
      name: message.flagname,
      threshold: message.configValue,
      value: message.nowValue,
      module: 'webChat',
      type: 'newMonitor'
    }
    commit(globalTypes.SET_NOTIFY, {tag: 'monitor', notify: data})
  }
}
/**
 * 邮件推送处理
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @returns {Promise<R>|Promise.<T>}
 * @private
 */
export const mailMonitorEventProcess = ({commit, state, rootState, dispatch}, event) => {
  event = event.Data
  if (event.im_monitor_type === 'agent') {
    commit(types.EVENT_MONITOR_MAIL, {event})
  }
}
/**
 * 保存自定义表头
 * @param commit
 * @param state
 * @param rootState
 * @param dispatch
 * @returns {Promise<R>|Promise.<T>}
 * @private
 */
export const saveTableHeader = ({commit, state, rootState, dispatch}, data) => {
  return report.saveReportTableHeader(data)
    .then(response => {
      data.Config = data.headers
      commit(types.TABLEHEADER_AGENT, {data: data})
    })
    .catch(err => {
      console.error(err)
      // 'message.default_tips'
    })
}

export function ctiMonitorProcess (evtJson, state, commit, rootState, dispatch) {
  globalField.dataJson = evtJson
  ctiMonitorPeer({commit, state, rootState, dispatch}, evtJson)
  ctiMonitorServiceNo({commit, state}, evtJson)
  ctiMonitorQueue({commit, state, rootState}, evtJson)
  ctiMonitorAccount({commit, state}, evtJson)
  ctiMonitorUpdateHeart({commit, state}, evtJson)
  ctiMonitorBusyWarning({commit, state, rootState, dispatch}, evtJson)
  monitorBusyWarning({commit, state, rootState, dispatch}, evtJson)
}
// 监控提醒
function monitorBusyWarning ({commit, state, rootState, dispatch}, evtJson) {
  if (evtJson.Event === 'WarningStatus') {
    let data = {
      condition: evtJson.Condition,
      name: evtJson.Name,
      threshold: evtJson.Threshold,
      value: evtJson.Value,
      module: 'call',
      type: 'newMonitor'
    }
    commit(globalTypes.SET_NOTIFY, {tag: 'monitor', notify: data})
  }
}
// 状态超时提醒
function ctiMonitorBusyWarning ({commit, state, rootState, dispatch}, evtJson) {
  if (evtJson.Event === 'UserBusyWarning') {
    let busyType = rootState.cti.globalLet.busyTypeName
    let busyTypeName = busyType ? busyType[evtJson.BusyType] : ''
    dispatch('getCache', {type: 'agents'}).then(agents => {
      let agent = filter(agents, {_id: evtJson.UserID})
      let userName = agent.length > 0 ? agent[0].displayName : ''
      let data = {userName, busyTypeName, module: 'call'}
      commit(globalTypes.SET_NOTIFY, {tag: 'monitor', notify: data})
    })
  }
}
// 更新监控心跳图数据
function ctiMonitorUpdateHeart ({commit, state}, evtJson) {
  if (evtJson.Event === 'HeartbeatStatus') {
    // IncomingData 呼入总数
    // IncomingComplete 呼入接听书
    // MisscomingData未接通总数
    // LimitcomingData  并发限制
    // queue 排队数
    let data = {
      pbx: evtJson.PBX,
      incomingData: evtJson.IncomingData,
      outboundData: evtJson.OutboundData,
      incomingCompleteData: evtJson.IncomingCompleteData,
      outboundCompleteData: evtJson.OutboundCompleteData,
      queueData: evtJson.QueueData,
      misscomingData: evtJson.MisscomingData || '',
      limitcomingData: evtJson.LimitcomingData || '',
      queue: evtJson.Queue || '',
      incomingComplete: evtJson.IncomingComplete || ''
    }
    commit(types.PHONE_HEARTBEAT, {pbx: evtJson.PBX, data})
  }
}
// 初始化心跳图
export const initHeartBeat = ({commit, state, rootState}, data) => {
  let req = {
    url: rootState.cti.globalLet._cti_url
  }
  req.jsonData = {
    Command: 'Action',
    Action: 'InitHeartBeat',
    ActionID: 'InitHeartBeat' + Math.random(),
    PBX: rootState.session.user.pbx,
    Account: rootState.session.user.account
  }
  // 值取当前数据，不取历史
  if (data) {
    req.jsonData.current = data.current
  }
  return monitor.initHeartBeat(req).then(response => {
    return response
  })
}
// 监控top10排名
export const queryMonitorAgentTopData = ({commit, state, rootState, dispatch}) => {
  return monitor.queryMonitorAgentTopData({account: rootState.session.user.account}).then(response => {
    if (response.success) {
      return response.data
    } else {
      return Promise.reject(response.message || 'default_tips')
    }
  }).then((reportData) => {
    return dispatch('getCache', {type: 'agents'}).then(agents => {
      reportData.imTop10.forEach((data) => {
        let agentId = data._id
        let agent = filter(agents, {_id: agentId})
        data.name = agent.length > 0 ? agent[0].displayName : ''
      })
      reportData.businessTop10.forEach((data) => {
        let agentId = data._id
        let agent = filter(agents, {_id: agentId})
        data.name = agent.length > 0 ? agent[0].displayName : ''
      })
      reportData.mailTop10.forEach((data) => {
        let agentId = data._id
        let agent = filter(agents, {_id: agentId})
        data.name = agent.length > 0 ? agent[0].displayName : ''
      })
      reportData.cdrCallInTop10.forEach((data) => {
        let agentId = data._id
        let agent = filter(agents, {_id: agentId})
        data.name = agent.length > 0 ? agent[0].displayName : ''
      })
      reportData.cdrCallOutTop10.forEach((data) => {
        let agentId = data._id
        let agent = filter(agents, {_id: agentId})
        data.name = agent.length > 0 ? agent[0].displayName : ''
      })
      return reportData
    })
  })
}
function ctiMonitorServiceNo ({commit, state}, evtJson) {
  if (evtJson.Event === 'TrunkStatus') {
    let displayName
    if (evtJson.DisplayName) {
      displayName = evtJson.DisplayName
      if (displayName.indexOf('serviceno-') === 0) {
        displayName = ''
      }
    }
    if (!window.phone_serviceNos[evtJson.ServiceNo]) {
      window.phone_serviceNos[evtJson.ServiceNo] = {
        serviceNo: evtJson.ServiceNo,
        inCalls: evtJson.InCalls,
        inLost: evtJson.InLost,
        inComplete: evtJson.InComplete,
        outCalls: 0,
        outComplete: 0,
        inQueueNow: 0, // 初始化值为0 更新时不赋值
        inQueueLeak: evtJson.InQueueLeak,
        displayName: displayName,
        pbx: evtJson.PBX,
        // inMaxLimit: evtJson.InMaxLimit,
        inLimit: evtJson.InLimit,
        inQueueNow: evtJson.InQueueWaiting || 0 // 排队数
      }
    } else {
      let serviceNo = window.phone_serviceNos[evtJson.ServiceNo]
      // serviceNo = {
      //   inCalls: evtJson.InCalls,
      //   inLost: evtJson.InLost,
      //   inComplete: evtJson.InComplete,
      //   outCalls: 0,
      //   outComplete: 0,
      //   displayName: displayName,
      //   // inMaxLimit: evtJson.InMaxLimit,
      //   inLimit: evtJson.InLimit
      // }
      serviceNo.inCalls = evtJson.InCalls
      serviceNo.inLost = evtJson.InLost
      serviceNo.inComplete = evtJson.InComplete
      serviceNo.outCalls = 0
      serviceNo.outComplete = 0
      serviceNo.inQueueLeak = evtJson.InQueueLeak
      serviceNo.displayName = displayName
      serviceNo.inLimit = evtJson.InLimit
      serviceNo.inQueueNow = evtJson.InQueueWaiting || 0 // 排队数
    }
    // let data = {
    //   serviceNo: evtJson.ServiceNo,
    //   numberInfo: serviceNo
    // }
    commit(ctiTypes.PHONE_SERVICENOS)
    ctiAction.phonePublishEvent(commit, state, 'EvtMonitorServiceNo', [window.phone_serviceNos[evtJson.ServiceNo]])
  } else if (evtJson.Event === 'Join' && evtJson.ServiceNo) {
    let queue = window.phone_serviceNos[evtJson.ServiceNo]
    if (queue) {
      queue.inQueueNow = queue.inQueueNow + 1
      handleQueueAndServieNoData('add', evtJson, commit)
      commit(ctiTypes.PHONE_SERVICENOS)
    }
  } else if (evtJson.Event === 'Leave' && evtJson.ServiceNo) {
    let queue = window.phone_serviceNos[evtJson.ServiceNo]
    if (queue) {
      queue.inQueueNow = queue.inQueueNow - 1
      if (queue.inQueueNow < 0) {
        queue.inQueueNow = 0
      }
      handleQueueAndServieNoData('delete', evtJson, commit)
      commit(ctiTypes.PHONE_SERVICENOS)
    }
  }
}

function handleQueueAndServieNoData (type, evtJson, commit) {
  let serviceNo = window.phone_serviceNos[evtJson.ServiceNo]
  let queue = window.phone_queues[evtJson.Queue]
  if (type === 'add') {
    if (serviceNo) {
      if (!serviceNo.QueueEntryState) {
        serviceNo.QueueEntryState = []
      }
      serviceNo.QueueEntryState.push(evtJson) // 新增进来的，号码列表加1
    }
    if (queue && queue.QueueEntryState) {
      queue.QueueEntryState.push(evtJson) // 新增进来的，号码列表加1
    }
  } else {
    if (serviceNo && serviceNo.QueueEntryState) {
      let serviceIndex = -1
      serviceNo.QueueEntryState.forEach((item, index) => {
        if (item.Uniqueid === evtJson.Uniqueid) {
          serviceIndex = index
          return false
        }
      })
      if (serviceIndex > -1) {
        serviceNo.QueueEntryState.splice(serviceIndex, 1) // 离开技能组的时候，要移除掉这个号码列表
      }
    }
    if (queue && queue.QueueEntryState) {
      let queueIndex = -1
      queue.QueueEntryState.forEach((item, index) => {
        if (item.Uniqueid === evtJson.Uniqueid) {
          queueIndex = index
          return false
        }
      })
      if (queueIndex > -1) {
        queue.QueueEntryState.splice(queueIndex, 1) // 离开技能组的时候，要移除掉这个号码列表
      }
    }
  }
  commit(types.UPDATE_CURRENT_QUEUE_SERVICENO, {evtJson})
}

function ctiMonitorPeer ({commit, state, rootState, dispatch}, evtJson) {
  //  Unlink  Hangup   都是挂断操作
//    normal transfer  dialTransfer 被动接收电话状态
//   通话结束Hangup (Unlink也当成Hangup处理,用来记录通话记录只接收此事件类型即可)
//  callIngWebchatSwitch功能，默认为开启的，如果没有设置过这个值，默认为开启
  let webchatSwitchFlag = false
  let Switch = rootState.session.user.callIngWebchatSwitch
  if (!Switch || Switch === 'yes') {
    webchatSwitchFlag = true
  }
  // console.log(evtJson.ChannelType)
  if (evtJson.Event === 'ChannelStatus') {
    if (evtJson.ChannelStatus === 'Hangup') {
      if (evtJson.ChannelType === 'normal' || evtJson.ChannelType === 'transfer' || evtJson.ChannelType === 'dialTransfer') {
        if (evtJson.UserID === rootState.session.user._id) { // 转接时，其他座席的事件不影响当前座席的来电添加备注功能
          let obj = {
            TransferReason: '',
            TransferAgent: ''
          }
          commit(ctiTypes.PHONE_TRANSFERREASON, obj) // 清空转接原因
          let data = {status: 'handUp', id: evtJson.Data.CallSheetID, channel: evtJson.ChannelType}
          commit(ctiTypes.CURRENT_CALL_UP_HANDUP, data) // 当前通话的状态和id
        }
      }
      if (evtJson.UserID === undefined) {
        return
      }
      //  需判断这个通话说是给自己的
      let webStatus = rootState.webchat.isOnOld
      if (evtJson.UserID === rootState.session.user._id && webchatSwitchFlag && evtJson.ChannelType && evtJson.ChannelType !== 'dialout' && webStatus === 'open') {
        dispatch('updateWebchatAutoClaimStatus', {status: webStatus, type: 'CallAutoSwitch', chatStatusDetail: 'open'}).then((res) => {
          commit(webchatTypes.SET_WEBCHAT_AUTOCLAIM_OLD, '')
          console.log(res)
        })
      }
    }
    let peer = ctiAction.ctiGetUserFromSip(evtJson.Exten)
    if (!peer) {
      return
    }
    // down的状态是座席接到电话的状态，只要有电话进来，都会走这个状态  qyg
    console.log('置空监控 铭感词')
    peer.sensitive = ''
    peer.sensitiveAgent = ''
    peer.sensitiveCustomer = ''
    window.phone_peers[evtJson.UserID].sensitiveObj = {}
    if (evtJson.ChannelStatus === 'Down') {
      peer.callStatus = 'Down'
      peer.channel = evtJson.Channel
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      // 拨打电话的时候，保存上次的在线咨询的状态
      // if (webchatSwitchFlag) {
      //   commit(webchatTypes.SET_WEBCHAT_AUTOCLAIM_OLD, rootState.webchat.isOn)
      // }
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    } else if (evtJson.ChannelStatus === 'Ring') { // 有了Ring才有通话记录 呼叫振铃Ring(话务进入呼叫中心触发的事件)
      if (evtJson.UserID === rootState.session.user._id) {
        commit(ctiTypes.IS_CALLING, true)
        if (evtJson.LinkedChannel && evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID) {
          // 转接和咨询的时候有LinkedChannel，解决转接和咨询打标签有记录但是操作日志的问题（后台的操作日志靠CallSheetID查询，标签和记录绑定没用上CallSheetID）
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.LinkedChannel.Data.CallSheetID)
        } else if (evtJson.Data && evtJson.Data.CallSheetID) { // 同样是外呼然后咨询有些账号有ring推送，有些账号没有，而且没有CallSheetID
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.Data.CallSheetID)
        }
      }
      peer.callStatus = 'Ring'
      peer.called = false
      peer.C5Status = evtJson.C5Status
      peer.timestamp = evtJson.Timestamp
      peer.channel = evtJson.Channel
      peer.queueName = ''
      if (evtJson.C5Status === 'OutboundCall' || evtJson.C5Status === 'InboundCall' || evtJson.C5Status === 'listen') {
        peer.callNo = evtJson.Data.ListenExten
      } else if (evtJson.FromDid) {
        peer.callNo = evtJson.FromDid
      }
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      if (evtJson.ChannelType === 'dialout') {
        if (evtJson.UserID === rootState.session.sessionId) {
          if (evtJson.Data.CallSheetID) {
            showDialoutData({commit, state, rootState}, evtJson)
          }
        }
      }
    } else if (evtJson.ChannelStatus === 'Ringing') { // 被呼振铃Ringing
      if (rootState.session && rootState.session.account) {
        // 来电数据丢失采集日志
        if (['N00000033603', 'N00000003731', 'T00000017832', 'T00000000003 '].includes(rootState.session.account.account)) {
          collectCallData(evtJson, '来电数据丢失采集日志')
        }
      }
      if (evtJson.UserID === rootState.session.user._id && webchatSwitchFlag && evtJson.ChannelType && evtJson.ChannelType !== 'dialout') {
        let status = rootState.webchat.isOn
        if (status === 'open') {
          let statusNew = 'close'
          commit(webchatTypes.SET_WEBCHAT_AUTOCLAIM_OLD, rootState.webchat.isOn)
          dispatch('updateWebchatAutoClaimStatus', {status: statusNew, type: 'CallAutoSwitch', chatStatusDetail: 'close'}).then((res) => {
            console.log(res)
          })
        }
      }
      if (evtJson.UserID === rootState.session.user._id) {
        commit(ctiTypes.IS_CALLING, true)
        if (evtJson.LinkedChannel && evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID) {
          // 转接和咨询的时候有LinkedChannel，解决转接和咨询打标签有记录但是操作日志的问题（后台的操作日志靠CallSheetID查询，标签和记录绑定没用上CallSheetID）
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.LinkedChannel.Data.CallSheetID)
        } else if (evtJson.Data && evtJson.Data.CallSheetID) {
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.Data.CallSheetID)
        }
      }
      peer.called = true
      peer.callStatus = 'Ringing'
      peer.C5Status = evtJson.C5Status
      peer.channel = evtJson.Channel
      peer.linkedChannel = evtJson.LinkedChannel.Channel
      if (evtJson.LinkedChannel) {
        peer.queueName = evtJson.LinkedChannel.QueueName
      }
      if (evtJson.ChannelType === 'dialTransfer') {
        peer.callNo = evtJson.FromDid
      } else {
        peer.callNo = evtJson.FromCid
      }
      peer.timestamp = evtJson.Timestamp
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
    } else if (evtJson.ChannelStatus === 'Up') { // 中间状态 up=>link
      if (rootState.session && rootState.session.account) { //
        if (['N00000057171', 'N00000052737', 'N00000053533'].includes(rootState.session.account.account)) {
          collectCallNote(evtJson)
        }
      }
      if (evtJson.ChannelType === 'normal' || evtJson.ChannelType === 'transfer' || evtJson.ChannelType === 'dialTransfer') {
        if (evtJson.UserID === rootState.session.user._id) { // 转接时，其他座席的事件不影响当前座席的来电添加备注功能
          let data = {status: 'up', id: evtJson.Data.CallSheetID || (evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID), channel: evtJson.ChannelType}
          commit(callTypes.UP_OR_HANDUP_FLAG, data) // 控制列表中编辑按钮的显示
          commit(ctiTypes.CURRENT_CALL_UP_HANDUP, data) // 当前通话的状态和id
        }
      }
      if (evtJson.ChannelType === 'listen') { // 监控里面的监听功能产生的通话的状态
        peer.callNo = evtJson.Data.ListenExten
        peer.timestamp = evtJson.Timestamp
        peer.C5Status = evtJson.C5Status
        peer.callStatus = evtJson.ChannelType
        peer.linked = true
        peer.channel = evtJson.Channel
        commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
        ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      }
    } else if (evtJson.ChannelStatus === 'Link') {
      // 接听电话的操作
      if (rootState.session && rootState.session.account) { //
        if (['N00000057171', 'N00000052737', 'N00000053533', 'N00000053147'].includes(rootState.session.account.account)) {
          collectCallNote(evtJson)
        }
      }
      if (evtJson.UserID === rootState.session.user._id) {
        if (evtJson.LinkedChannel && evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID) {
          // 转接和咨询的时候有LinkedChannel，解决转接和咨询打标签有记录但是操作日志的问题（后台的操作日志靠CallSheetID查询，标签和记录绑定没用上CallSheetID）
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.LinkedChannel.Data.CallSheetID)
        } else if (evtJson.Data && evtJson.Data.CallSheetID) {
          commit(ctiTypes.CURRENTCALLSHEETID, evtJson.Data.CallSheetID)
        }
      }
      peer.timestamp = evtJson.Timestamp
      peer.C5Status = evtJson.C5Status
      peer.linked = true
      peer.channel = evtJson.Channel
      peer.linkedChannel = evtJson.LinkedChannel.Channel
      peer.callStatus = evtJson.ChannelType
      if (evtJson.LinkedChannel) {
        peer.queueName = evtJson.LinkedChannel.QueueName
      }
      if (evtJson.ChannelType === 'dialout' || evtJson.ChannelType === 'dialTransfer') {
        peer.callNo = evtJson.LinkedChannel.FromDid
      } else {
        peer.callNo = evtJson.LinkedChannel.FromCid
        let NewData = {id: evtJson.Data.CallSheetID, status: evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallStatus}
        commit(callTypes.SET_CDR_CALL_NEW_STATUS, NewData)
      }
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      if (evtJson.ChannelType === 'normal' || evtJson.ChannelType === 'transfer' || evtJson.ChannelType === 'dialTransfer') { // 来电，来电转接，外呼转接
        if (evtJson.UserID === rootState.session.user._id) { // 转接时，其他座席的事件不影响当前座席的来电添加备注功能
          let data = {status: 'up', id: evtJson.Data.CallSheetID || (evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID), channel: evtJson.ChannelType}
          let NewData = {id: evtJson.Data.CallSheetID, newId: evtJson.LinkedChannel && evtJson.LinkedChannel.Data && evtJson.LinkedChannel.Data.CallSheetID}
          commit(callTypes.UP_OR_HANDUP_FLAG, data) // 控制列表中编辑按钮的显示
          commit(ctiTypes.CURRENT_CALL_UP_HANDUP, data) // 当前通话的状态和id
          if (evtJson.ChannelType === 'dialTransfer') {
            commit(callTypes.SET_CDR_CALL_NEW_CALLID, NewData)
          }
        }
      }
      console.log(evtJson.ChannelType)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
    } else if (evtJson.ChannelStatus === 'Unlink') {
      //  挂断操作
      // if (evtJson.UserID === rootState.session.user._id && webchatSwitchFlag && evtJson.ChannelType && evtJson.ChannelType !== 'dialout') {
      //   dispatch('updateWebchatAutoClaimStatus', {status: rootState.webchat.isOnOld, type: 'CallAutoSwitch'}).then((res) => {
      //     console.log(res)
      //   })
      // }
    } else if (evtJson.ChannelStatus === 'Hangup') { // 挂断
      if (evtJson.ChannelType === 'listen') {
        if (state.globalLet.phone_data._curChannel === evtJson.Channel) {
          if (evtJson.ChannelType === 'listen') {
            commit(ctiTypes.PHONE_DATA, {phoneData: {_otherChannel: ''}})
            ctiAction.phonePublishEvent(commit, state, 'EvtEndListen', [])
          }
        }
      }
      if (peer.channel === evtJson.Channel) {
        if (state.globalLet.phone_data._otherChannel === evtJson.Channel &&
          (state.globalLet._cti_stateDescription[state.globalLet._cti_currentState] === 'listening' || state.globalLet._cti_stateDescription[state.globalLet._cti_currentState] === 'listened')) {
          ctiAction.phoneHangup({commit, state})
        }
      }
      peer.callNo = ''
      peer.callStatus = 'Idle'
      peer.timestamp = evtJson.Timestamp
      peer.channel = ''
      peer.linkedChannel = ''
      peer.queueName = ''
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
    }
  } else if (evtJson.Event === 'UserStatus') {
    let isRegistered = false
    let peerToCommit = {}
    if (evtJson.PeerStatus === 'Registered') {
      isRegistered = true
    }
    if (evtJson.BusyType && evtJson.BusyType === '98') {
      evtJson.BusyType = '99'
    }
    if (!window.phone_peers[evtJson.UserID]) {
      peerToCommit = {
        exten: evtJson.Exten,
        sipNo: evtJson.SipNum,
        name: evtJson.User,
        DisplayName: evtJson.DisplayName,
        loginExten: evtJson.LoginExten,
        peerStatus: evtJson.PeerStatus,
        status: evtJson.Status,
        C5Status: evtJson.C5Status,
        busy: evtJson.Busy,
        extenType: evtJson.ExtenType,
        login: evtJson.Login,
        userId: evtJson.UserID,
        user: evtJson.User,
        localNo: evtJson.Local,
        register: isRegistered,
        InCalls: evtJson.InCalls + evtJson.TransferCalls, // 转接+呼入=呼入总数
        InComplete: evtJson.InComplete + evtJson.TransferComplete, // 转接成功数+呼入成功数=呼入总成功数
        TransferCalls: evtJson.TransferCalls,
        TransferComplete: evtJson.TransferComplete,
        OutCalls: evtJson.OutCalls,
        OutComplete: evtJson.OutComplete,
        DialinTimeLength: evtJson.DialinTimeLength,
        DialoutTimeLength: evtJson.DialoutTimeLength,
        linked: false,
        channel: '',
        linkedChannel: '',
        called: false,
        callStatus: 'Idle',
        callNo: '',
        timestamp: evtJson.Login ? (evtJson.BusyTimestamp) : '',
        busyTimestamp: evtJson.BusyTimestamp,
        loginTimestamp: evtJson.LoginTimestamp,
        busyType: evtJson.BusyType,
        statusTime: evtJson.StatusTime,
        statusTimestamp: evtJson.StatusTimestamp,
        // pinyin: cnToSpell.getSpell(evtJson.DisplayName),
        pbx: evtJson.PBX,
        version: evtJson.Version
      }
      window.phone_peers[evtJson.UserID] = peerToCommit
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      if (evtJson.SipNum) {
        ctiUpdateUserSip(commit, evtJson.SipNum, peerToCommit)
      }
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peerToCommit])
    } else {
      let peer = window.phone_peers[evtJson.UserID]
      peer.peerStatus = evtJson.PeerStatus
      peer.status = evtJson.Status
      peer.exten = evtJson.Exten
      peer.sipNo = evtJson.SipNum
      peer.C5Status = evtJson.C5Status
      peer.busy = evtJson.Busy
      peer.extenType = evtJson.ExtenType
      peer.login = evtJson.Login
      peer.loginExten = evtJson.LoginExten
      peer.name = evtJson.User
      peer.DisplayName = evtJson.DisplayName
      peer.userId = evtJson.UserID
      peer.user = evtJson.User
      peer.localNo = evtJson.Local
      peer.register = isRegistered
      peer.InCalls = evtJson.InCalls + evtJson.TransferCalls // 转接+呼入=呼入总数
      peer.InComplete = evtJson.InComplete + evtJson.TransferComplete
      peer.TransferCalls = evtJson.TransferCalls
      peer.TransferComplete = evtJson.TransferComplete
      peer.DialinTimeLength = evtJson.DialinTimeLength
      peer.DialoutTimeLength = evtJson.DialoutTimeLength
      peer.OutCalls = evtJson.OutCalls
      peer.OutComplete = evtJson.OutComplete
      peer.busyTimestamp = evtJson.BusyTimestamp
      peer.loginTimestamp = evtJson.LoginTimestamp
      peer.busyType = evtJson.BusyType
      peer.statusTime = evtJson.StatusTime
      peer.statusTimestamp = evtJson.StatusTimestamp
      peer.timestamp = peer.login ? (peer.busyTimestamp) : ''
      peer.version = evtJson.Version
      peer.sensitive = ''
      peer.sensitiveAgent = ''
      peer.sensitiveCustomer = ''
      window.phone_peers[evtJson.UserID].sensitiveObj = {}
      if (evtJson.SipNum) {
        ctiUpdateUserSip(commit, evtJson.SipNum, peer)
      }
      if (!peer.sipNo) {
        peer.callStatus = 'Idle'
        peer.callNo = ''
      }
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    }
  } else if (evtJson.Event === 'UserBusy') {
    if (window.phone_peers[evtJson.UserID]) {
      let peer = window.phone_peers[evtJson.UserID]
      // let peerToCommit = {}
      peer.busy = evtJson.Busy
      peer.busyType = evtJson.BusyType
      peer.busyTimestamp = evtJson.BusyTimestamp
      peer.statusTime = evtJson.StatusTime
      peer.statusTimestamp = evtJson.StatusTimestamp
      peer.timestamp = peer.login ? (peer.busyTimestamp) : ''
      peer.loginTimestamp = evtJson.LoginTimestamp
      peer.sensitive = ''
      peer.sensitiveAgent = ''
      peer.sensitiveCustomer = ''
      window.phone_peers[evtJson.UserID].sensitiveObj = {}
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
    }
  } else if (evtJson.Event === 'UserCallsUpdate') {
    if (window.phone_peers[evtJson.UserID]) {
      let peer = window.phone_peers[evtJson.UserID]
      // 转接+呼入=呼入总数
      peer.InCalls = evtJson.InCalls + evtJson.TransferCalls
      // 转接成功数+呼入成功数=呼入总成功数
      peer.InComplete = evtJson.InComplete + evtJson.TransferComplete
      peer.TransferCalls = evtJson.TransferCalls
      peer.TransferComplete = evtJson.TransferComplete
      peer.DialoutTimeLength = evtJson.DialoutTimeLength
      peer.DialinTimeLength = evtJson.DialinTimeLength
      peer.OutCalls = evtJson.OutCalls
      peer.OutComplete = evtJson.OutComplete
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    }
  } else if (evtJson.Event === 'UserSignIn') {
    if (window.phone_peers[evtJson.UserID]) {
      let peer = window.phone_peers[evtJson.UserID]
      peer.extenType = evtJson.ExtenType
      peer.login = evtJson.Login
      peer.sipNo = evtJson.SipNum
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    }
  } else if (evtJson.Event === 'UserSignOut') {
    if (window.phone_peers[evtJson.UserID]) {
      let peer = window.phone_peers[evtJson.UserID]
      peer.extenType = evtJson.ExtenType
      peer.sipNo = evtJson.SipNum
      peer.login = evtJson.Login
      commit(types.AGENT_STATE_CHANGE, evtJson.UserID)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    }
  } else if (evtJson.Event === 'PeerStatus') {
    let isRegistered = false
    if (evtJson.PeerStatus === 'Registered') {
      isRegistered = true
    }
    let peer = ctiAction.ctiGetUserFromSip(evtJson.Exten)
    if (peer) {
      peer.register = isRegistered
      peer.status = evtJson.Status
      if (peer.userId === state.globalLet.phone_data.userId) {
        commit(ctiTypes.PHONE_DATA, {phoneData: {Status: evtJson.Status}})
      }
      commit(types.AGENT_STATE_CHANGE, peer.userId)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorPeer', [peer])
      ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
    }
  }
}
function handleQuequeWarn (state,rootState, commit, evtJson, queueItem) {
  if (rootState.session.user.type === 'manager' && rootState.session.user.notifyStatus && rootState.session.user.notifyStatus.indexOf('monitor') > -1) { // 是监控座席 && 开监控提醒
    const queueWarning = rootState.monitor.queueWarning
    if (queueWarning) {
      handleQuequeWarnDetail(commit, queueItem, queueWarning, evtJson)
    }
  }
}
function collectCallNote (currentCtiEvent) {
  try {
    const error = {
      env: {
        browser: {name: 'Chrome', version: '67.0.3396.99'},
        os: 'Mac',
        userAgent: 'Mozilla/5.0'
      },
      extra: {
        componentName: ''
      },
      errorType: 'TypeError',
      message: '来电无法展示小笔',
      referrer: 'http://kf.com/customer',
      stacktrace: {
        frames: []
      },
      trimHeadFrames: 1,
      url: '',
      exception: {
        values: [{
          type: 'TypeError',
          value: JSON.stringify(currentCtiEvent),
          stacktrace: {
            frames: []
          }
        }]
      }
    }
    let req = {
      data: error,
      action: 'app.collect.collectVueErrorInfo'
    }
    http.fetch(req, 'post')
      .then((res) => {
      })
      .catch(err => {
        console.error(err)
      })
  } catch (err) {
    console.log(err)
  }
}
// 来电数据丢失采集日志
function collectCallData (currentCtiEvent, message) {
  try {
    const error = {
      env: {
        browser: {name: 'Chrome', version: '67.0.3396.99'},
        os: 'Mac',
        userAgent: 'Mozilla/5.0'
      },
      extra: {
        componentName: ''
      },
      errorType: 'TypeError',
      message: message ? message : '来电小笔没有展示',
      referrer: 'http://kf.com/customer',
      stacktrace: {
        frames: []
      },
      trimHeadFrames: 1,
      url: '',
      exception: {
        values: [{
          type: 'TypeError',
          value: JSON.stringify(currentCtiEvent),
          stacktrace: {
            frames: []
          }
        }]
      }
    }
    let req = {
      data: error,
      action: 'app.collect.collectVueErrorInfo'
    }
    http.fetch(req, 'post')
      .then((res) => {
      })
      .catch(err => {
        console.error(err)
      })
  } catch (err) {
    console.log(err)
  }
}
function handleQuequeWarnDetail (commit, queueItem, queueWarning, evtJson) {
  if (!evtJson.Queue) {
    return false
  }
  let queueConfig = {}
  if (queueWarning && queueWarning.config) {
    queueWarning.config.forEach(item => {
      if (item.queue === evtJson.Queue) { // 匹配技能组信息
        queueConfig = item
        return
      }
    })
    if (queueConfig.condition === 'over') {
      if (queueItem.queueWaitCount > queueConfig.value && queueConfig.value >= 0) {
        commit(globalTypes.SET_NOTIFY, { tag: 'monitorNew', notify: {queueName: queueItem.queueName, codeName: '当前排队数', queueWaitCount: queueItem.queueWaitCount} })
      }
    } else if (queueConfig.condition === 'less') {
      if (queueItem.queueWaitCount < queueConfig.value && queueConfig.value > 0) {
        commit(globalTypes.SET_NOTIFY, { tag: 'monitorNew', notify: {queueName: queueItem.queueName, codeName: '当前排队数', queueWaitCount: queueItem.queueWaitCount} })
      }
    } else if (queueConfig.condition === 'equal') {
      if (queueItem.queueWaitCount == queueConfig.value) {
        commit(globalTypes.SET_NOTIFY, { tag: 'monitorNew', notify: {queueName: queueItem.queueName, codeName: '当前排队数', queueWaitCount: queueItem.queueWaitCount} })
      }
    }
  }
}
function ctiMonitorQueue ({commit, state, rootState}, evtJson) {
  // queue的重新赋值是为了还原老版代码，解决EvtMonitorQueue事件回来的数据缺失的问题导致电话条排队数延迟
  if (evtJson.Event === 'QueueParams') {
    let queueItem = {}
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      if (evtJson.Removed) {
        // queueItem.removed = true
        queue.removed = true
      }
      // queueItem.queueName = evtJson.DisplayName
      queue.queueName = evtJson.DisplayName
      // queueItem.idleAgentCount = evtJson.Members - evtJson.BusyMembers
      queue.idleAgentCount = evtJson.RegisterCount - evtJson.BusyMembers
      // queueItem.busyAgentCount = evtJson.BusyMembers
      queue.busyAgentCount = evtJson.BusyMembers - evtJson.CallUserCount
      // queueItem.totalAgentCount = evtJson.Members
      queue.registerCount = evtJson.RegisterCount
      queue.unregisterCount = evtJson.Members - evtJson.RegisterCount
      queue.callUserCount = evtJson.CallUserCount
      queue.totalAgentCount = evtJson.Members
      // queueItem.queueWaitCount = evtJson.Calls
      queue.queueWaitCount = evtJson.Calls
      // queueItem.abadonedCalls = evtJson.Abandoned
      queue.abadonedCalls = evtJson.Abandoned
      // queueItem.totalCalls = evtJson.TotalCalls
      queue.totalCalls = evtJson.TotalCalls
      // queueItem.DisplayName = evtJson.DisplayName
      queue.DisplayName = evtJson.DisplayName
      // queueItem.members = {}
      queue.queueAbandon = evtJson.QueueAbandon
      queue.NotTransfer = evtJson.NotTransfer || false
      queue.ServiceQuality = evtJson.ServiceQuality || '0.00'
      queue.members = {}
      for (let i in evtJson.QueueMember) {
        let member = evtJson.QueueMember[i]
        // queueItem.members[member] = member
        queue.members[member] = member
      }
      queue.QueueEntryState = evtJson.QueueEntryState ? evtJson.QueueEntryState : []
      commit(ctiTypes.PHONE_QUEUES)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queue, 'needWaitCount'], '', rootState)
      handleQuequeWarn(state, rootState, commit, evtJson, queue)
      // initQueueAndServieNoData(queue)
    } else {
      queueItem = {
        queueName: evtJson.DisplayName,
        queueId: evtJson.Queue,
        idleAgentCount: (evtJson.RegisterCount || 0) - evtJson.BusyMembers,
        busyAgentCount: evtJson.BusyMembers - evtJson.CallUserCount || 0,
        registerCount: evtJson.RegisterCount || 0,
        unregisterCount: evtJson.Members - evtJson.RegisterCount,
        callUserCount: evtJson.CallUserCount || 0,
        totalAgentCount: evtJson.Members,
        queueWaitCount: evtJson.Calls,
        abadonedCalls: evtJson.Abandoned, // 未接听数
        queueAbandon: evtJson.QueueAbandon, // 排队放弃数
        DisplayName: evtJson.DisplayName,
        totalCalls: evtJson.TotalCalls,
        members: {},
        removed: false,
        pbx: evtJson.PBX,
        NotTransfer: evtJson.NotTransfer || false,
        ServiceQuality: evtJson.ServiceQuality || '0.00'
      }
      for (let i in evtJson.QueueMember) {
        let member = evtJson.QueueMember[i]
        queueItem.members[member] = member
      }
      queueItem.QueueEntryState = evtJson.QueueEntryState ? evtJson.QueueEntryState : []
      window.phone_queues[evtJson.Queue] = queueItem
      commit(ctiTypes.PHONE_QUEUES)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queueItem, 'needWaitCount'], '', rootState)
      handleQuequeWarn(state, rootState, commit, evtJson, queueItem)
      initQueueAndServieNoData(queueItem)
    }
  } else if (evtJson.Event === 'QueueMemberAdded') {
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      if (!queue.members[evtJson.Exten]) {
        queue.members[evtJson.Exten] = evtJson.Exten
        queue.totalAgentCount = queue.totalAgentCount + 1
        commit(ctiTypes.PHONE_QUEUES)
        ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
      }
    }
  } else if (evtJson.Event === 'QueueMemberRemoved') {
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      if (queue.members[evtJson.Exten]) {
        delete queue.members[evtJson.Exten]
        queue.totalAgentCount = queue.totalAgentCount - 1
        commit(ctiTypes.PHONE_QUEUES)
        //   当技能组 删除座席时 更新技能组内座席 空闲忙碌等信息
        ctiAction.ctiUpdateQueueInfo(state, commit, rootState)
        //  以下为原代码  没有做 座席状态信息的更新
        // ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queue, 'noNeedWaitCount'], '', rootState)
      }
    }
  } else if (evtJson.Event === 'Join' && evtJson.Queue) {
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      queue.queueWaitCount = queue.queueWaitCount + 1
      commit(ctiTypes.PHONE_QUEUES)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queue, 'needWaitCount'], '', rootState)
      handleQuequeWarn(state, rootState, commit, evtJson, queue)
    }
  } else if (evtJson.Event === 'Leave' && evtJson.Queue) {
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      queue.totalCalls = queue.totalCalls + 1
      queue.queueWaitCount = queue.queueWaitCount - 1
      if (queue.queueWaitCount < 0) {
        queue.queueWaitCount = 0
      }
      commit(ctiTypes.PHONE_QUEUES)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queue, 'needWaitCount'], '', rootState)
      handleQuequeWarn(state, rootState, commit, evtJson, queue)
    }
  } else if (evtJson.Event === 'QueueCallerAbandon') {
    let queue = ctiQueryQueueItem(state, evtJson)
    if (queue) {
      queue.abadonedCalls = queue.abadonedCalls + 1
      queue.queueAbandon = evtJson.QueueAbandon
      commit(ctiTypes.PHONE_QUEUES)
      ctiAction.phonePublishEvent(commit, state, 'EvtMonitorQueue', [queue, 'noNeedWaitCount'], '', rootState)
    }
  }
}

function initQueueAndServieNoData (queue) {
  queue.QueueEntryState.forEach(item => {
    if (item.ServiceNo) {
      let serviceNo = window.phone_serviceNos[item.ServiceNo]
      if (serviceNo && !serviceNo.QueueEntryState) {
        serviceNo.QueueEntryState = []
      }
      if (serviceNo) {
        serviceNo.QueueEntryState.push(item)
      }
    }
  })
}

function ctiMonitorAccount ({commit, state}, evtJson) {
  if (evtJson.Event === 'AccountStatus') {
    if (!state.globalLet.phone_accountCalls[evtJson.PBX]) {
      let account = {
        account: evtJson.Account,
        inCalls: evtJson.InCalls,
        outComplete: evtJson.OutComplete,
        inComplete: evtJson.InComplete,
        outCalls: evtJson.OutCalls,
        inCallsPerHour: evtJson.InCallsPerHour,
        currentOutCalls: evtJson.CurrentOutCalls,
        pbx: evtJson.PBX,
        inType: evtJson.InType,
        inCompletePerHour: evtJson.InCompletePerHour,
        outCallsPerHour: evtJson.OutCallsPerHour,
        currentInCalls: evtJson.CurrentInCalls,
        outCompletePerHour: evtJson.OutCompletePerHour
      }
      commit(ctiTypes.PHONE_ACCOUNTCALLS, {pbx: evtJson.PBX, account: account})
      ctiAction.phonePublishEvent(commit, state, 'EvtAccountCalls', [account])
    } else {
      let account = {
        account: evtJson.Account,
        inCalls: evtJson.InCalls,
        outComplete: evtJson.OutComplete,
        inComplete: evtJson.InComplete,
        outCalls: evtJson.OutCalls,
        inCallsPerHour: evtJson.InCallsPerHour,
        currentOutCalls: evtJson.CurrentOutCalls,
        pbx: evtJson.PBX,
        inType: evtJson.InType,
        inCompletePerHour: evtJson.InCompletePerHour,
        outCallsPerHour: evtJson.OutCallsPerHour,
        currentInCalls: evtJson.CurrentInCalls,
        outCompletePerHour: evtJson.OutCompletePerHour
      }
      commit(ctiTypes.PHONE_ACCOUNTCALLS, {pbx: evtJson.PBX, account: account})
      ctiAction.phonePublishEvent(commit, state, 'EvtAccountCalls', [account])
    }
  }
}

function ctiUpdateUserSip (commit, sipNo, peer) {
  window._phone_peersFromSip[sipNo] = peer
}

function ctiQueryQueueItem (state, evtJson) {
  return window.phone_queues[evtJson.Queue]
}

function showDialoutData ({commit, state, rootState}, evtJson) {
  let result = {}
  if (evtJson) {
    result.CallNo = evtJson.FromCid
    result.CalledNo = evtJson.FromDid
    result.CallSheetID = evtJson.Data.CallSheetID
    result.CallType = evtJson.ChannelType
    result.Ring = evtJson.Timestamp
    commit('call/CURRENT_TRANS_ID', {callSheetId: evtJson.Data.CallSheetID, type: 'cdr_outbound'})
    commit('call/SET_CALL_INFO', {data: {CONNECT_TYPE: 'dialout', CALLED_NO: evtJson.FromDid, CALL_NO: evtJson.FromCid}, type: 'cdr_outbound'})
    getCache({commit, state: rootState}, {type: 'agents', id: evtJson.UserID}).then((res) => {
      result.Agent = res.exten
      // result.ActionID = evtJson.ACTION_ID;外呼接口调用外呼 是否会有这个值
      result.Province = evtJson.CalleeProvince
      result.District = evtJson.CalleeCity
      result.CallID = evtJson.Uniqueid
      ctiAction.showDialoutUrlOrInPopupCust({commit, state, rootState}, result)
    })
  }
}
/**
 * 1.点击座席状态日志链接(操作查看对应的响应事件)
 * @param data
 * data:{"BEGIN_TIME":"2017-09-14 00:00:00",  起始时间
   * "END_TIME":"2017-09-14 23:59:59",          终止时间
   * "pageSize":10,                             每页显示条数
   * "ACTION_TYPE":"login"}                     日志类型
 * 2.点击查询按钮的响应事件（走的是统一方法，参数个数不同）
 * data:{"AGENT":"5e87f760-2217-11e6-9ec7-b101597a9db6",  当前登录座席
   * "includeSubordinate":false,                            显示已选座席下级
   * "BEGIN_TIME":"2017-09-14 00:00:00",
   * "END_TIME":"2017-09-14 23:59:59",
   * "reportType":"call_report_agent",
   * "selectedAgent":"5e87f760-2217-11e6-9ec7-b101597a9db6",所选座席
   * "StartingAndEndingTime":false,                         仅显示最初登录时间和最后退出时间
   * "pageSize":10,
   * "ACTION_TYPE":"login"}
 * 3.查看对应的参数格式
 * data:{"BEGIN_TIME":"2017-09-14 15:44:38",
   * "END_TIME":"null",
   * "pageSize":10,
   * "AGENT":"1e3c34d0-2930-11e6-b8cf-a923f8fdcf8e",
   * "ACTION_TYPE":"busy"}
 * 4.翻页对应的参数格式：
 * data:{"AGENT":"",
   * "includeSubordinate":false,
   * "BEGIN_TIME":"2017-09-01 00:00:00",
   * "END_TIME":"2017-09-14 23:59:59",
   * "reportType":"call_report_agent",
   * "selectedAgent":"",
   * "StartingAndEndingTime":false,
   * "page":"2",     页码
   * "pageSize":10,
   * "ACTION_TYPE":"login"}
 * @returns {*}
 * 5. 仅显示最初登录时间和最后退出时间参数格式
 * data:{"AGENT":"",
   * "includeSubordinate":false,
   * "BEGIN_TIME":"2017-09-01 00:00:00",
   * "END_TIME":"2017-09-14 23:59:59",
   * "reportType":"call_report_agent",
   * "selectedAgent":"",
   * "StartingAndEndingTime":false,
   * "pageSize":10,
   * "ACTION_TYPE":"login"}
 */
export const queryCdrPeer = ({commit, state, rootState, dispatch}, data) => {
  delete data.date
  return monitor.queryCdrPeer(data)
    .then(response => {
      return response
    })
}
export const getCdrPeerSummary = ({commit, state, rootState, dispatch}, data) => {
  delete data.date
  return monitor.getCdrPeerSummary(data)
    .then(response => {
      return dealReportRes(response)
    })
}
export const queryImStatusLogReport = ({commit, state, rootState, dispatch}, data) => {
  delete data.date
  return monitor.queryImStatusLogReport(data)
    .then(response => {
      return dealReportRes(response)
    })
}
export const getImStatusDetails = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getImStatusDetails(data)
    .then(response => {
      return response
    })
}
export const getLoginStatusLogs = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getLoginStatusLogs(data)
    .then(response => {
      return response
    })
}
export const getMoreStatusLogs = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getMoreStatusLogs(data)
    .then(response => {
      return response
    })
}
export const getlogincdrpeer = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getlogincdrpeer(data)
    .then(response => {
      return response
    })
}
export const getBusyCdrPeer = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getBusyCdrPeer(data)
    .then(response => {
      return response
    })
}
export const getCdrPeerStatusDetails = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getCdrPeerStatusDetails(data)
    .then(response => {
      return response
    })
}
export const exportCdrPeer = ({commit, state, rootState, dispatch}, data) => {
  return monitor.exportCdrPeer(data)
    .then(response => {
      if (response.Succeed) {
        commit(globalTypes.SET_FILEDOWNLOAD, { path: response.path, isSession: true })
      } else {
      }
    })
}
export const updateMonitorConfig = ({commit, state, rootState, dispatch}, data) => {
  return monitor.updateMonitorConfig(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
}
export const getMonitorList = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getMonitorList(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
}
export const getUserMonitorList = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getUserMonitorList(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
}
export const removeMonitorConfig = ({commit, state, rootState, dispatch}, data) => {
  return monitor.removeMonitorConfig(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
}
export const showMonitorConfig = ({commit, state, rootState, dispatch}, data) => {
  return monitor.showMonitorConfig(data)
    .then(response => {
      if (response.success) {
        return response
      }
    })
}
export const getAgentMonitorHeaderConfig = ({commit, state, rootState, dispatch}, data) => {
  return report.getReportTableHeader(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const queryAccountMoniterBusyNotice = ({commit, state, rootState, dispatch}, data) => {
  return monitor.queryAccountMoniterBusyNotice(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const updateAccountMoniterBusyNotice = ({commit, state, rootState, dispatch}, data) => {
  return monitor.updateAccountMoniterBusyNotice(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getRemoteControlMonitorInfo = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getRemoteControlMonitorInfo(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getRemoteControlMonitorList = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getRemoteControlMonitorList(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getCallInDataIn6Hours = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getCallInDataIn6Hours(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const queryMonitorWarningCfg = ({commit, state, rootState, dispatch}, data) => {
  return monitor.queryMonitorWarningCfg(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const updateMonitorWarningCfg = ({commit, state, rootState, dispatch}, data) => {
  return monitor.updateMonitorWarningCfg(data).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getAdvisoryChannelCount = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getAdvisoryChannelCount({account: rootState.session.account.account}).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getCallInAreaData = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getCallInAreaData({pbx: rootState.session.user.pbx}).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getProvinceCodes = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getProvinceCodes({pbx: rootState.session.user.pbx}).then(response => {
    if (response.success) {
      return response
    }
  })
}
export const getWebChatDataIn6Hours = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getWebChatDataIn6Hours(data).then(response => {
    if (response.success) {
      return response
    }
  })
}

export const getMonitorSensitiveWordsHistory = ({commit, state, rootState, dispatch}, data) => {
  return monitor.getMonitorSensitiveWordsHistory(data).then(response => {
    if (response.success) {
      if (response.data && response.data.length > 0) {
        response.data.forEach((item) => {
          window.phone_peers[item.callAgent].sensitive = item.sensitiveWords
          commit('AGENT_STATE_CHANGE', item.callAgent)
        })
      }
    }
  })
}

export const updateMonitorQueueWarningCfg = ({commit, state, rootState, dispatch}, data) => {
  return monitor.updateMonitorQueueWarningCfg(data).then(response => {
    return response
  })
}
export const queryMonitorQueueWarningCfg = ({commit, state, rootState, dispatch}, data) => {
  return monitor.queryMonitorQueueWarningCfg(data).then(response => {
    return response
  })
}

function catchError (message, source, lineno, colno, error) {
  if (globalField.dataJson) {
    if (['N00000033603', 'N00000003731', 'T00000017832', 'T00000000003'].includes(globalField.dataJson.Account)) {
      let errorData = {
        message,
        source,
        lineno,
        colno,
        error
      }
      console.log(errorData, 'errorData')
      collectCallData(errorData, '来电错误日志')
    }
  }
  return true // 将代码错误定格在捕获阶段
}
window.onerror = catchError
